import { childrenProps } from '@/components/ProForm/interface';

/**
 * 根据树最后一级的value 查询每一级的value
 */
export const treeGetValues = (tree: childrenProps[], value: string | number) => {
  for (let item of tree) {
    const values: any[] = [];
    if (item.value === value) {
      values.push(item.value);
      return values;
    }
    // 递归获取value
    const { flag, result } = treeFindChildrenValue(item, value, values) || {};

    if (flag) {
      return result;
    }
  }
  return [];
};

/**
 * 递归获取value
 */
export const treeFindChildrenValue = (item: childrenProps, value: string | number, result: any[]) => {
  if (item?.children?.length) {
    for (let i of item.children) {
      let values = [];
      // 记录当前层级value
      values.push(item.value);

      // 有子节点继续查找
      if (i.children) {
        treeFindChildrenValue(i, value, values);
      }

      // 找到value直接返回
      if (i.value === value) {
        values.push(i.value);
        return {
          flag: true,
          result: values
        };
      }
    }
  }
};
